package indi.cyh.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CYH
 * @className FastjsonConfiguration
 * @description fastjson配置
 * @date 2024/12/31 15:52
 */
@Configuration
public class FastjsonConfiguration {

    /**
     * 配置fastjosn作为接口数据的解析工具
     *
     * @param
     * @return org.springframework.boot.autoconfigure.http.HttpMessageConverters
     * @author CYH
     * @date 2024/12/31 15:57
     **/
    @Bean
    public HttpMessageConverters fastJsonConfigure() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = getFastJsonConfig();

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        // 创建支持的媒体类型列表
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        // 设置支持的媒体类型
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
        // 设置默认字符集为 UTF-8
        fastJsonHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
        // 返回 HttpMessageConverters 实例
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }

    /**
     * fastjson 全局序列化配置
     *
     * @param
     * @return com.alibaba.fastjson2.support.config.FastJsonConfig
     * @author CYH
     * @date 2024/12/31 15:57
     **/
    private static FastJsonConfig getFastJsonConfig() {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //fastjson2 默认格式为yyyy-MM-dd HH:mm 无需重新设置
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setWriterFeatures(
                //long 转 string 丢失精度问题
                JSONWriter.Feature.WriteLongAsString,
                // 保留map空的字段
                JSONWriter.Feature.WriteMapNullValue,
                //日期格式转换
                JSONWriter.Feature.PrettyFormat
        );
        return fastJsonConfig;
    }
}
